(function (root, factory) {
    if(typeof define === 'function' && define.amd)
        define(['jquery','CryptoJS'], factory);
    else
        root["api"] = factory(window.$,window.CryptoJS);
}(this, function ($,CryptoJS) {

    var site_root ="http://yunchuang.ddns.net:8018/";
    var api = {
        //客户管理——根据条件获取客户池中的客户数量
        Get_Pool_Customer_Count: function(pool,params){
            return this.BaseGetRequest(site_root+pool+ "/GetCustomerCountOfPool", params)
        },
        //客户管理——根据条件获取某客户池中的客户信息列表
        Get_Pool_Customer_List: function(pool,params){
            return this.BaseGetRequest(site_root+pool+ "/GetCustomerOfPool", params)
        },
        //客户管理——根据条件获取下一条客户信息
        Get_Pool_Customer_Next: function(pool,params){
            return this.BaseGetRequest( site_root+pool+ "/GetNextCustomer", params)
        },
        // 客户管理——根据联系方式判断客户是否存在，是否成交
        Get_Check_Customer_Exists: function(params){
            return this.BaseGetRequest(site_root + "Customer/CheckCustomerIsExistsByContact", params)
        },
        // 客户管理——新增客户
        Post_Add_Customer: function(params){
            return this.BasePostRequest(site_root + "Customer/AddCustomer", params)
        },
        // 客户管理——根据客户Id获取客户信息
        Get_Customer_Info: function(params){
            return this.BaseGetRequest(site_root + "Customer/GetCustomerOfStaffPoolById",params)
        },
        // 客户管理——编辑客户
        Post_Edit_Customer: function(params){
            return this.BasePostRequest(site_root + "Customer/EditCustomer", params)
        },
        // 客户管理——根据客户Id获取该客户的所有联系方式
        Get_Customer_All_Contact: function(params){
            return this.BaseGetRequest(site_root + "Customer/GetCustomerAllContact", params)
        },
        // 客户管理——给客户添加一个亲友及联系方式
        Post_Add_Relative_Contact: function(params){
            return this.BasePostRequest(site_root + "Customer/AddRelativeContact", params)
        },
        // 客户管理——更改联系方式的主联系方式
        Post_Change_Contact_Usually: function(params){
            return this.BasePostRequest(site_root + "Customer/ChangeContactUsually", params)
        },
        // 客户管理——删除客户的亲友
        Post_Del_Customer_Relative: function(params){
            return this.BasePostRequest(site_root + "Customer/DelCustomerRelative", params)
        },
        // 客户管理——修改客户联系方式
        Post_Edit_Customer_Contact: function(params){
            return this.BasePostRequest(site_root + "Customer/EditCustomerContact", params)
        },
        // 客户管理——废弃客户
        Post_Abandon_Customer: function(params){
            return this.BasePostRequest(site_root + "Customer/AbandonCustomerByIdList", params)
        },
        // 客户管理——恢复废弃客户
        Post_Recovered_Customer: function(params){
            return this.BasePostRequest(site_root + "Customer/RecoveredCustomerByIdList", params)
        },
        // 客户管理——获取客户来源类型
        Get_Customer_SourceType_Option: function(params){
            return this.BaseGetRequest(site_root + "CustomerSourceType/GetCustomerSourceTypeOption", params)
        },
        // 客户管理——新增客户来源类型
        Post_Add_Customer_SourceType: function(params){
            return this.BasePostRequest(site_root + "CustomerSourceType/AddCustomerSourceType", params)
        },
        // 客户管理——删除客户来源类型
        Post_Del_Customer_SourceType: function(params){
            return this.BasePostRequest(site_root + "CustomerSourceType/DelCustomerSourceType", params)
        },
        // 客户管理——获取客户自定义字段
        Get_Customer_Custom_Property: function(params){
            return this.BaseGetRequest( site_root + "CustomProperty/GetNotDeleteCustomProperty", params)
        },
        // 客户管理——将客户从一个公客池转到另一公客池
        Post_Shift_Customer_ToOtherDept: function(params){
            return this.BasePostRequest(site_root + "DeptPool/ShiftCustomerToOtherDept", params)
        },
        // 客户管理——将客户转到私客
        Post_Shift_Customer_ToStaff: function(params){
            return this.BasePostRequest(site_root + "DeptPool/ShiftCustomerToStaff", params)
        },
        // 客户管理——获取客户来源终端
        Get_Cusotmer_SourceClient: function(params){
            return this.BaseGetRequest(site_root + "Enumber/SourceClientEnumberEntity", params)
        },
        // 客户管理——将客户转到公客
        Post_Shift_Customer_ToDept: function(params){
            return this.BasePostRequest(site_root + "StaffPool/ShiftCustomerToDept", params)
        },
        // 客户管理——将客户转给其他销售员
        Post_Shift_Customer_ToOtherStaff: function(params){
            return this.BasePostRequest(site_root + "StaffPool/ShiftCustomerToOtherStaff", params)
        },
        // 客户管理——根据客户Id和销售员Id获取跟进关系
        Get_Track_By_Customer_And_Salesperson: function(params){
            return this.BaseGetRequest(site_root + "Track/GetTrackListByCustomerAndSalesperson", params)
        },
        // 客户管理——断开跟进关系
        Post_Stop_Track_Of_Customer: function(params){
            return this.BasePostRequest(site_root + "Track/StopOneTrackOfCustomer", params)
        },
        // 客户管理——获取回访信息
        Get_Visit_Info: function(params){
            return this.BaseGetRequest(site_root + "Visit/GetVisitInfoList", params)
        },
        // 客户管理——获取回访计划
        Get_Visit_Plan: function(params){
            return this.BaseGetRequest(site_root + "Visit/GetVisitPlan", params)
        },
        // 客户管理——提交回访
        Post_Submit_Visit_Record: function(params){
            return this.BasePostRequest(site_root + "Visit/SubmitVisitRecord", params)
        },
        // 客户管理——根据客户Id获取该客户的带看回访信息
        Get_Visit_Record_Of_Looked_House: function(params){
            return this.BaseGetRequest( site_root + "Visit/GetVisitRecordOfLookedHouse", params)
        },
        // 客户管理——根据客户Id获取该客户的成交回访信息
        Get_Visit_Record_Of_Traded: function(params){
            return this.BaseGetRequest( site_root + "Visit/GetVisitRecordOfTraded", params)
        },
        // 客户管理——根据销售员Id,获取该销售员的所有回访计划
        Get_All_Visit_Plan_By_SalespersonId: function(params){
            return this.BaseGetRequest(  site_root + "Visit/GetAllVisitPlanBySalespersonId"
                , params)
        },
        // 客户管理——获取所有的客户等级
        Get_All_Level: function(params){
            return this.BaseGetRequest(site_root + "CustomerLevel/GetAllNotDeleteLevel"
                , params)
        },
        // 客户管理——获取所有的大客户等级
        Get_All_Big_Level: function(params){
            return this.BaseGetRequest(site_root + "CustomerLevel/GetAllNotDeletBigeLevel", params)
        },
        // 客户管理——新增大客户等级
        Post_Add_Big_Level: function(params){
            return this.BasePostRequest(site_root + "CustomerLevel/AddBigLevel", params)
        },
        // 客户管理——删除大客户等级
        Post_Del_Big_Level: function(params){
            return this.BasePostRequest(site_root + "CustomerLevel/DelBigLevel", params)
        },

        //todo :
        PostEditLand: function (params) {
            return this.BasePostRequest(url.postEditLand, params)
        },
        //todo :待确定
        PostAddLand: function (params) {
            return this.BasePostRequest(url.postAddLand, params)
        },
        //todo :待确定
        PostEditWorkshop: function (params) {
            return this.BasePostRequest(url.postEditWorkshop, params)
        },
        //todo :待确定
        PostAddWorkshop: function (params) {
            return this.BasePostRequest(url.postAddWorkshop, params)
        },
        //todo :待确定
        PostEditPrivateHouse: function (params) {
            return this.BasePostRequest(url.postEditPrivateHouse, params)
        },
        //todo :待确定
        PostAddPrivateHouse: function (params) {
            return this.BasePostRequest(url.postAddPrivateHouse, params)
        },
        //todo :待确定
        PostEditGarden: function (params) {
            return this.BasePostRequest(url.postEditGarden, params)
        },
        //todo :待确定
        PostAddGarden: function (params) {
            return this.BasePostRequest(url.postAddGarden, params)
        },
        ////todo: 接口定义错误,应该传入参数companyid,请使用 fetchPositionList.
        fetchJobList: function () {
            throw ('接口定义错误,应该传入参数companyid,请使用 fetchPositionList.');
        },
        fetchPositionList: function (params) {
            return this.BaseGetRequest(site_root+ 'position/list', params);
        },
        PostJobAdd: function (params) {
            return this.BasePostRequest(site_root+'position/add', params)
        },
        PostJobEdit: function (params) {
            return this.BasePostRequest(site_root+'position/edit', params)
        },
        PostJobDel: function (params) {
            return this.BasePostRequest(site_root +'position/delete', params)
        },
        PostLogin: function (params) {
            strToken=this.generateLoginToken(params.UserName,params.Password,site_root + "v1/account/login");
            params.token=strToken;
            return $.ajax({
                url: site_root + "v1/account/login",
                type: 'post',
                //contentType: "application/json; charset=utf-8",//--
                data:  params,
                dataType: "json"
            })
        },
        //todo : 名字和Id,需要其他信息自动填充.
        GetGardenNameList: function (params) {
            return this.BaseGetRequest(url.GardenNameList, params)
        },
        // 获取小区具体信息列表
        //todo: 结合页面讨论结构。
        GetGardenList: function (params) {
            //"../data/house/mock_garden_obj.json"
            return this.BaseGetRequest(url.GardenList, params)
        },
        // todo 后台还未实现 '../../data/house/mock_map_plot.json'
        fetchMapMarkerData: function (params) {
            return this.BaseGetRequest(url.MAP_MARKER_DATA, params);
        },
        fetchPlotSearchData: function (params) {
            return this.BaseGetRequest(  site_root + "realestate/search",  params);
        },


        GetAllPermissions: function () {
            return this.BaseGetRequest(　 site_root + 'v1/idaccess/Permissions');
        },
        SavePlot: function (params) {
            return this.BasePostRequest(site_root + "realestate/create", params);
        },

        fetchQnToken: function () {
            return this.BasePostRequest('http://127.0.0.1:3000/upload_token',params)
        },
        //todo  '../../data/house/mock_map_house.json'
        fetchMapHouseList: function (params) {
            return this.BaseGetRequest(url.MAP_HOUSE_LIST, params);
        },
        SaveOrganization: function (params) {

            return this.BasePostRequest(site_root + "v1/organization/save",params)
        },
        DeleteOrganization: function (params) {
            return this.BasePostRequest(site_root + "v1/organization/delete",params)
        },
        GetOrganizaitonNode: function (params) {
            return this.BaseGetRequest(site_root +"v1/organization/node", params);
        },
        GetOrganizaitonNodes: function (params) {

            return this.BaseGetRequest(site_root + "v1/organization/nodes", params);

        },
        //获取包含员工的组织结构树
        Get_Node_Tree: function (params) {
            return this.BaseGetRequest( site_root + "Organization/GetNodeTree", params);
        },

        fetchStaffList: function (params) {
            return this.BaseGetRequest(site_root + "v1/staffs/", params);
        },

        editStaff: function (params) {
            return this.BasePostRequest(site_root + "v1/staffs/",params)
        },
        delStaff: function (params) {
            return this.BasePostRequest(site_root + "v1/staffs/delete",params )
        },
        getCustomArea: function (param) {
            return this.BaseGetRequest(site_root + "customarea/getall", param);
        },
        //todo
        fetchPlanData: function (params) {
            return this.BaseGetRequest(url.fetchPlanData, params);
        },
        //根据公司Id获取员工信息
        Get_Staff_By_CompanyId: function (params) {
            return this.BaseGetRequest(site_root + "staff/GetStaffByCompanyId/", params);
        },
        BaseAjaxRequest: function (url, params) {
            strToken=this.generateApiToken(url);
            if(!params){
                params={};
            }
            params.token=strToken;
            return $.ajax({
                url: url,
                type: 'post',
                // contentType: "application/json; charset=utf-8",
                data: params,//JSON.stringify(params),
                dataType: "json"
            })
        },
        BaseGetRequest: function (strUrl,params) {
            strToken=this.generateApiToken(strUrl);
            if(!params){
                params={};
            }
            params.token=strToken;
            return $.getJSON(strUrl, params)
            // return $.ajax({
            //     url: strUrl,
            //     type: 'get',
            //     data:  params,
            //     dataType: "json"
            // })
        },
        BasePostRequest: function (strUrl,params) {
            strToken=this.generateApiToken(strUrl);
            if(!params){
                params={};
            }
            params.token=strToken;
            return $.post(strUrl, params)
            // return $.ajax({
            //     url: strUrl,
            //     type: 'get',
            //     data:  params,
            //     dataType: "json"
            // })
        },
        generateLoginToken: function (username, password,url) {
            localStorage.removeItem('SecurityManager.key');
            localStorage.removeItem('SecurityManager.Secret');
            url=url.toLowerCase();
            var ticks = ((new Date().getTime() * 10000) + 621355968000000000);
            //window.console.log(ticks);
            var key = CryptoJS.enc.Base64.stringify(CryptoJS.HmacSHA256([password, ticks].join(':'), ticks.toString()));
            //window.console.log(key);
            var message = [username, url, navigator.userAgent.replace(/ \.NET.+;/, ''), ticks].join(':');
            //window.console.log(message);
            var hash = CryptoJS.HmacSHA256(message, key);
            var token = CryptoJS.enc.Base64.stringify(hash);
            var tokenId = [username, ticks].join(':');
            var tokenStr = CryptoJS.enc.Utf8.parse([token, tokenId].join(':'));
            return CryptoJS.enc.Base64.stringify(tokenStr);
        },
        generateApiToken: function (url) {
            if (!localStorage['SecurityManager.key'] || !localStorage['SecurityManager.Secret']) {
                top.location.replace(window.location.origin+'/views/login/login.html');
            }
            url=url.toLowerCase();
            var ticks = ((new Date().getTime() * 10000) + 621355968000000000);
            var message = [localStorage['SecurityManager.key'],url, navigator.userAgent.replace(/ \.NET.+;/, ''), ticks].join(':');
            var hash = CryptoJS.HmacSHA256(message, localStorage['SecurityManager.Secret']);
            var token = CryptoJS.enc.Base64.stringify(hash);
            var tokenId = [localStorage['SecurityManager.key'], ticks].join(':');
            var tokenStr = CryptoJS.enc.Utf8.parse([token, tokenId].join(':'));
            return CryptoJS.enc.Base64.stringify(tokenStr);
        },
    };

    //全局的ajax访问，处理ajax清求时session超时
    $.ajaxSetup({
        contentType: "application/x-www-form-urlencoded;charset=utf-8",
        error:function (a,b,c) {
  console.log(a+b+c)
        },
        complete: function (XMLHttpRequest, textStatus) {
            if (XMLHttpRequest.status == 401) {
                //window.location.replace(XMLHttpRequest.getResponseHeader("returnurl"));
                if(window.location.href===window.location.origin+'/views/login/login.html'){
                }else{
                    top.location.replace(window.location.origin + '/views/login/login.html');
                }
            }
            //通过XMLHttpRequest取得响应头，sessionstatus，
            var sessionstatus = XMLHttpRequest.getResponseHeader("sessionstatus");
            if (sessionstatus == "timeout") {
                //如果超时就处理 ，指定要跳转的页面(比如登陆页)
                if(window.location.href===window.location.origin+'/views/login/login.html'){

                }else{
                    window.location.replace(window.location.origin+'/views/login/login.html');
                }
            }
        }
    });
    return api;
}));
